package com.example.blade.activity.browser

import android.os.Build
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import cn.vove7.bottomdialog.BottomDialogActivity
import cn.vove7.bottomdialog.builder.buttons
import cn.vove7.bottomdialog.builder.mutableList
import cn.vove7.bottomdialog.util.ObservableList
import com.blankj.utilcode.constant.RegexConstants
import com.blankj.utilcode.util.*
import com.drake.channel.sendEvent
import com.drake.channel.sendTag
import com.example.blade.activity.browser.temporary.WebViewActivity.Companion.filePath
import nico.styTool.R


class PointIcon(mWebView: WebView, activity: AppCompatActivity, itemId: Int) {
    init {
        when (itemId) {
            R.id.item_left -> {
                if (mWebView.canGoBack()) {
                    mWebView.goBack()
                }
            }
            R.id.item_right -> {
                if (mWebView.canGoForward()) {
                    mWebView.goForward()
                }
            }
            R.id.item_share -> {

            }
            R.id.item_copy -> {
                 nico.styTool.Utils.setClipboard(mWebView.url)
            }
            R.id.item_exit -> {
                handleFinish(activity)
            }
            R.id.item_null -> {
                nico.styTool.Utils.setToast(Learn)
                mWebView.loadUrl("https://aang.xyz/jx/?url=${mWebView.url}")
            }
            R.id.item_history -> {
                if (FileUtils.createOrExistsFile(filePath)) {
                    BottomDialogActivity.builder(activity) {
                        val list = ObservableList.build<String?> {
                            addAll(FileIOUtils.readFile2List(filePath).reversed())
                        }
                        mutableList(list) { _, _, s, _ ->
                            mWebView.loadUrl(replaceText(s.toString()))
                        }
                        buttons {
                            negativeButton {
                                it.dismiss()
                            }
                        }
                    }
                }
            }
            R.id.item_visibility -> {
                sendTag("visibility")
            }
            else -> println("Null")
        }
    }

    private fun handleFinish(me: AppCompatActivity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            me.finishAfterTransition()
        } else {
            me.finish()
        }
    }

    private fun replaceText(s: String) = RegexUtils.getMatches(RegexConstants.REGEX_URL, s)[0]

    companion object {
        private const val Learn = "此功能仅供个人学习、研究之用，请勿用于商业用途\n请在下载后24小时内删除"
    }
}